"""
系统配置数据模型
"""

from datetime import datetime
from typing import Dict, Any, Optional, Union
from pymongo import MongoClient
from app.config import Config


class ConfigModel:
    """系统配置数据模型类"""
    
    def __init__(self):
        self.client = MongoClient(Config.MONGODB_URI)
        self.db = self.client.md2dockit
        self.collection = self.db.system_config
        
        # 创建索引
        self._create_indexes()
        
        # 初始化默认配置
        self._init_default_config()
    
    def _create_indexes(self):
        """创建必要的索引"""
        try:
            self.collection.create_index("config_key", unique=True)
        except Exception as e:
            print(f"创建配置索引失败: {e}")
    
    def _init_default_config(self):
        """初始化默认配置"""
        default_configs = [
            {
                "config_key": "max_file_size",
                "config_value": str(5 * 1024 * 1024),  # 5MB
                "config_type": "integer",
                "description": "单文件最大上传大小（字节）",
                "is_editable": True
            },
            {
                "config_key": "max_concurrent_tasks",
                "config_value": "10",
                "config_type": "integer",
                "description": "系统最大并发任务数",
                "is_editable": True
            },
            {
                "config_key": "file_retention_hours",
                "config_value": "24",
                "config_type": "integer",
                "description": "文件保留时间（小时）",
                "is_editable": True
            },
            {
                "config_key": "conversion_timeout",
                "config_value": "30",
                "config_type": "integer",
                "description": "转换超时时间（秒）",
                "is_editable": True
            }
        ]
        
        for config in default_configs:
            self.set_config(
                config["config_key"],
                config["config_value"],
                config["config_type"],
                config["description"],
                config["is_editable"]
            )
    
    def get_config(self, config_key: str) -> Optional[Dict[str, Any]]:
        """
        获取配置项
        
        Args:
            config_key: 配置键
            
        Returns:
            Optional[Dict]: 配置信息，不存在则返回None
        """
        try:
            config = self.collection.find_one({"config_key": config_key})
            if config:
                config.pop('_id', None)
            return config
        except Exception as e:
            print(f"获取配置失败: {e}")
            return None
    
    def get_config_value(self, config_key: str, default_value: Any = None) -> Any:
        """
        获取配置值
        
        Args:
            config_key: 配置键
            default_value: 默认值
            
        Returns:
            Any: 配置值
        """
        config = self.get_config(config_key)
        if not config:
            return default_value
        
        value = config["config_value"]
        config_type = config.get("config_type", "string")
        
        # 类型转换
        try:
            if config_type == "integer":
                return int(value)
            elif config_type == "boolean":
                return value.lower() in ("true", "1", "yes", "on")
            elif config_type == "json":
                import json
                return json.loads(value)
            else:
                return value
        except (ValueError, TypeError):
            return default_value
    
    def set_config(self, config_key: str, config_value: str, 
                  config_type: str = "string", description: str = "", 
                  is_editable: bool = True) -> bool:
        """
        设置配置项
        
        Args:
            config_key: 配置键
            config_value: 配置值
            config_type: 配置类型
            description: 描述
            is_editable: 是否可编辑
            
        Returns:
            bool: 设置是否成功
        """
        try:
            config_data = {
                "config_key": config_key,
                "config_value": str(config_value),
                "config_type": config_type,
                "description": description,
                "is_editable": is_editable,
                "updated_at": datetime.utcnow()
            }
            
            result = self.collection.update_one(
                {"config_key": config_key},
                {"$set": config_data},
                upsert=True
            )
            return True
        except Exception as e:
            print(f"设置配置失败: {e}")
            return False
    
    def get_all_configs(self) -> Dict[str, Any]:
        """
        获取所有配置
        
        Returns:
            Dict: 所有配置项
        """
        try:
            configs = {}
            for config in self.collection.find({}, {"_id": 0}):
                key = config["config_key"]
                configs[key] = self.get_config_value(key)
            return configs
        except Exception as e:
            print(f"获取所有配置失败: {e}")
            return {}
    
    def delete_config(self, config_key: str) -> bool:
        """
        删除配置项
        
        Args:
            config_key: 配置键
            
        Returns:
            bool: 删除是否成功
        """
        try:
            # 检查是否可编辑
            config = self.get_config(config_key)
            if config and not config.get("is_editable", True):
                return False
            
            result = self.collection.delete_one({"config_key": config_key})
            return result.deleted_count > 0
        except Exception as e:
            print(f"删除配置失败: {e}")
            return False